import { Card, Descriptions, Button, Input, Dropdown, Menu, Divider, Form, Icon, message, Avatar, PageHeader, Popover, Tooltip, } from 'antd';
import React, { useState, useEffect, useContext, useRef } from 'react';
import { connect } from 'dva';
import { sizeFormat, stringToDate } from "@/generic/Utils";
import { HTTP_STATUS, PATH_LENGTH } from "@/generic/ConfigParams";
import { handleUpdate, downloadMenu } from "./DirsTable";
import { deleteApiRule } from '../service';
import ShareForm from "./ShareForm";

import logo from '@/assets/logo.png';
import FileViewer from 'react-file-viewer';


export const getDirPath = (filePath, separator="/") => {
    
    return filePath.split(separator).slice(0, -1).join(separator) || separator
    // // usr
    // let _path = filePath.split(separator).slice(PATH_LENGTH);
    // return _path.length > 1 ? _path.join(separator) : separator;
}

const vdiskFullName = (disk) => {

    switch (disk) {
        case 'pub':
            return '/public'
    
        default:
            return '/private';
    }
}

const EditInput = props => {

    const { file, onEdit, inputRef, } = props;

    const inputBlock = (
        <div style={{paddingRight: "16px"}}>
            <Input 
                ref={inputRef}
                defaultValue={file.name.split('.')[0]}
                placeholder="请输入新名称" 
                autoFocus 
                suffix={file ? file.ext : ""} 
                onChange={() => { console.log(" input is change !", );}}
            />
        </div>
    );

    return (
        onEdit
            ? inputBlock
            : <span>{file.name}</span>
    );
}

const FileDetails = props => {

    let { file, vdiskName,  } = props.location.state;
    const { dispatch } = props;
    const [onEdit, setOnEdit] = useState(false);
    const inputRef = useRef();

    useEffect(() =>{
        console.log("==>> file", file)
    }, [])

    const backTo = () => {
        // console.log("==>> getDirPath", getDirPath(file.path))
        
        props.history.push(`${vdiskFullName(vdiskName)}/all`, {
            currentPath: getDirPath(file.path)
        });
    }

    const deleteOption = async () => {

        // 删除
        let hide = message.loading("删除中...")
        const response = await deleteApiRule({ disk: vdiskName, location: `/${file.name}` });
        hide();
        if (response.ok) {
            // 跳转
            backTo();
            return;
        }
        message.error(`${HTTP_STATUS[response.status]}`);
    }

    const extraRender = () => {

        const mockSubmit = async () => {
            // fields, vdiskName, currentPath, src, rw = true
            const success = await handleUpdate(inputRef.current.state, vdiskName, getDirPath(file.path), file);
            if (success) {
                file.name = `${inputRef.current.state.value}${file.ext}`;
                file.path = `${file.path.split('/').slice(0, -1).join("/")}/${file.name}`;
                setOnEdit(false);
                return
            }
            console.error("file info update error!", success)
        }

        const onEditing = (
            <>
                <Icon type="close" style={{ color: '#7f7f7f' }} onClick={() => setOnEdit(false)}/>
                <Divider type="vertical"/>
                <Icon type="check" style={{ color: '#52c41a' }} onClick={mockSubmit}/>
            </>
        );
        return (
            onEdit
            ? onEditing
            : <Icon type="edit" theme="twoTone" onClick={() => setOnEdit(true)} />
        );
    }
    const content = (
        <Descriptions>
            {
                file.owner && <Descriptions.Item label="所有人">{file.owner || "测试人员"}</Descriptions.Item>
            }
            <Descriptions.Item label="所有人">{file.owner || "测试人员"}</Descriptions.Item>
            <Descriptions.Item label="大小">{sizeFormat(file.size)}</Descriptions.Item>
            <Descriptions.Item label="类型">{file.ext}</Descriptions.Item>
            <Descriptions.Item label="密级">{file.cl}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{stringToDate(file.created)}</Descriptions.Item>
            <Descriptions.Item label="修改时间">{stringToDate(file.modified)}</Descriptions.Item>
            {
                file.desc && <Descriptions.Item label="描述">{file.desc || "这是一个测试描述，目的是让界面更加充实！"}</Descriptions.Item>
            }
            <Descriptions.Item label="描述">{file.desc || "这是一个测试描述，目的是让界面更加充实！"}</Descriptions.Item>
            
        </Descriptions>
    );

    const footer = (
        <>
            <div style={{ float: "left", height:'32px', lineHeight:'32px' }}>
                <Icon type="arrow-left" onClick={backTo}/>
            </div>
            <div style={{ float: "right", }}>
                <Dropdown overlay={downloadMenu(file, vdiskName)} placement="bottomCenter" trigger={['click']}>
                    <Button style={{ marginRight: '12px' }}>下载</Button>
                </Dropdown>
                <Button type="danger" onClick={deleteOption}>删除</Button>
            </div>
            <div style={{ float: "right", height: '32px', lineHeight: '32px', marginRight: '16px' }}>
                <Icon
                    type="share-alt"
                    onClick={() => {
                        dispatch({
                            type: 'fileDetail/UpdateModalVisible',
                            payload: true
                        });
                    }}
                />
            </div>
        </>
    );

    return (
        <>
            <div style={{backgroundColor: "#fff"}}>
                <Card 
                    title={<EditInput file={file} onEdit={onEdit} inputRef={inputRef}/>} 
                    extra={extraRender()}
                >
                    {content}
                    {/* <Divider />
                    <FileViewer
                        fileType='pdf'
                        filePath={require('./good.pdf')}
                    /> */}
                    <Divider />
                    {footer}
                </Card>
            </div>
            
            <ShareForm 
                onSubmit={async value => {

                    const success = await handleUpdate(value, vdisk(), currentPath, srcfile);
                    if (success) {

                        setModalVisible(false);
                        tableRefresh();
                    }
                }}
                onCancel={() => {
                    dispatch({
                        type: 'fileDetail/UpdateModalVisible',
                        payload: false
                    });
                }}
                {...props}
            />
            
        </>
    );
}

export default connect(({ fileDetail }) => ({
    ...fileDetail
}))(FileDetails);